package com.shengdou.as.slopsapptest.Activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.shengdou.as.slopsapptest.MyApplication;
import com.shengdou.as.slopsapptest.R;
import com.shengdou.as.slopsapptest.base.BaseActivity;
import com.shengdou.as.slopsapptest.bean.FactoryNameBean;
import com.shengdou.as.slopsapptest.bean.person;
import com.shengdou.as.slopsapptest.utils.CheckPhoneUtil;
import com.shengdou.as.slopsapptest.utils.Constants;
import com.shengdou.as.slopsapptest.utils.DateUtils;
import com.shengdou.as.slopsapptest.utils.FileUtils;
import com.shengdou.as.slopsapptest.utils.HttpUtils;
import com.shengdou.as.slopsapptest.utils.LogUtil;
import com.shengdou.as.slopsapptest.utils.NetConstant;
import com.shengdou.as.slopsapptest.utils.SHA1;
import com.shengdou.as.slopsapptest.utils.SharedPreferenceUtil;
import com.shengdou.as.slopsapptest.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;


/**
 * 登录
 */
public class LoginActivity extends BaseActivity {
    private TextView mTxtFactory;
    private LinearLayout mLinFactory;
    private ArrayList<FactoryNameBean.AddrBean> arrayList;
    private PopupWindow popup = null;
    public static Context context;
    private String ipInfo;
    private EditText et_phone, et_password;
    private String phoneNumber, password;
    private Map<String, String> params = new HashMap<>();
    private Gson gson;
    private static int s;
    private String rid;
    private MyAdapter adapter;//厂家适配器
    private String factoryUrl, factoryName;//选择的厂家的ip,name
    private Handler mHandlerAll = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constants.FACTORYADD:
                    //获取所有厂的信息
                    LogUtil.e("===厂名信息=====", msg.obj.toString());
                    FactoryNameBean factoryNameBean = gson.fromJson(msg.obj.toString(), FactoryNameBean.class);
                    arrayList = new ArrayList<>();
                    if (factoryNameBean.getAddr() != null) {
                        arrayList.addAll(factoryNameBean.getAddr());
                    }
                    break;
                case Constants.IMAGESERVLET:
                    LogUtil.e("result", msg.obj.toString());
                    try {
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        String status = jsonObject.getString("status_text");
                        String session_id = jsonObject.getString("session_id");
                        SharedPreferenceUtil.savePreferenceString(LoginActivity.this, "session_id", session_id);
                        DialogCode(status);
//                        ToastUtils.showToast(status);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    params.clear();
                    break;
                case Constants.LOGIN:
                    LogUtil.e("result", msg.obj.toString());
                    person persons = gson.fromJson(msg.obj.toString(), person.class);
                    if (factoryUrl != null && !factoryUrl.equals("")) {
                        SharedPreferenceUtil.savePreferenceString(MyApplication.ApplicationContext, "ipInfo", factoryUrl);
                    }
//                    SharedPreferenceUtil.savePreferenceString(LoginActivity.this, "FactoryName", factoryName);
                    boolean flag = FileUtils.saveObject(LoginActivity.this, "person", persons);
                    if (flag) {
                        if (persons.getMobile() != null && persons.getFactory_name() != null
                                && persons.getReal_name() != null) {
                            LogUtil.e(persons.getFactory_name());
                            SharedPreferenceUtil.savePreferenceString(LoginActivity.this, "mobile", persons.getMobile());
                            SharedPreferenceUtil.savePreferenceString(LoginActivity.this, "real_name", persons.getReal_name());
                            SharedPreferenceUtil.savePreferenceString(LoginActivity.this, "portrait", persons.getPortrait());//头像
                            SharedPreferenceUtil.savePreferenceString(LoginActivity.this, "FactoryName", persons.getFactory_name());
                            SharedPreferenceUtil.savePreferenceInt(LoginActivity.this, "level", persons.getLevel());
                            SharedPreferenceUtil.savePreferenceFloat(LoginActivity.this, "newHeight", 3.5f);
                        }
                        /*for (person.FactoryBean pivotBean : persons.getFactory()) {
                            //向服务器修改自己的类别
                            JPushInterface.setAlias(LoginActivity.this, "dou_" + pivotBean.getPivot().getFactory_id(), null);
                        }*/
                        if (SharedPreferenceUtil.getPreferenceString(LoginActivity.this, "ipInfo") != null) {
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    }
                    break;

            }
        }
    };// 全局handler

    //获取的验证码提示
    private void DialogCode(String status) {
        final AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
        alertDialog.show();
        alertDialog.getWindow().setContentView(R.layout.dialog_code);
        TextView code = (TextView) alertDialog.getWindow().findViewById(R.id.txt_code);
        code.setText(status);
        alertDialog.getWindow().findViewById(R.id.dialog_verify_cancle).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                alertDialog.cancel();
            }
        });
        alertDialog.getWindow().findViewById(R.id.dialog_verify_go).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                alertDialog.cancel();
            }
        });
    }

    private TextView mGetCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        init();
    }

    //获取厂名信息
    private void gainFactoryName() {
        String user_agent = OkHttpUtils.head("User-Agent").getHeaders().get("User-Agent");
        String key = "NzsefUbG40HfzIDF";
        LogUtil.e(user_agent + "===User-Agent" + DateUtils.getStringToDate());
        String sha = SHA1.getStringSHA1(user_agent + key + DateUtils.getStringToDate());
        LogUtil.e("加密后的信息" + sha);
        HttpUtils.postFactory(mHandlerAll, NetConstant.FACTORYADD, null, Constants.FACTORYADD, LoginActivity.this);
    }

    private void init() {
        context = this;
        mLinFactory = (LinearLayout) findViewById(R.id.lineat_factory);
        mTxtFactory = (TextView) findViewById(R.id.txt_factory);
        SharedPreferenceUtil.savePreferenceString(LoginActivity.this, "session_id", null);
        ipInfo = SharedPreferenceUtil.getPreferenceString(LoginActivity.this, "ipInfo");
        gson = new Gson();
        mGetCode = (TextView) findViewById(R.id.txt_incode);
        et_phone = (EditText) findViewById(R.id.et_phone);
        et_password = (EditText) findViewById(R.id.et_passwor);
        et_phone.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
        et_password.setFilters(new InputFilter[]{new InputFilter.LengthFilter(16)});
        rid = JPushInterface.getRegistrationID(getApplicationContext());
        LogUtil.e("极光返回的id", rid);
        gainFactoryName(); //获取厂名信息
        mLinFactory.setVisibility(View.VISIBLE);
    }


    public void onTabClick(View view) {
        phoneNumber = et_phone.getText().toString().trim();
        password = et_password.getText().toString().trim();
        switch (view.getId()) {
            case R.id.btn_login:
                //登录
                if (mLinFactory.getVisibility() == View.VISIBLE) {
                    if ((factoryName == null || factoryName.equals(""))
                            && (factoryUrl == null || factoryUrl.equals(""))) {
                        ToastUtils.showToast(R.string.factory_name);
                        return;
                    }
                }
                if (!CheckPhoneUtil.isPhoneNumberValid(phoneNumber)) {
                    ToastUtils.showToast(R.string.phone_format);
                    return;
                } else if (password == null || password.equals("")) {
                    ToastUtils.showToast(R.string.password_code);
                    return;
                } else if (CheckPhoneUtil.isPhoneNumberValid(phoneNumber) && password != null
                        && mTxtFactory.getText().toString().trim() != null) {
                    LogUtil.e("极光返回的idsss", rid);
                    params.put("mobile", phoneNumber);
                    params.put("code", password);
                    params.put("registration_id", rid);
                    LogUtil.e("session_id", SharedPreferenceUtil.getPreferenceString(LoginActivity.this, "session_id"));
                    if (factoryUrl != null && !factoryUrl.equals("")) {
                        HttpUtils.postFirst(mHandlerAll, factoryUrl + "/app/account/smsLogin", params, Constants.LOGIN, LoginActivity.this);
                    }
                }
                break;
            case R.id.txt_incode:
                //获取验证码
                if (mLinFactory.getVisibility() == View.VISIBLE) {
                    if ((factoryName == null || factoryName.equals(""))
                            && (factoryUrl == null || factoryUrl.equals(""))) {
                        ToastUtils.showToast(R.string.factory_name);
                        return;
                    }
                }
                if (!CheckPhoneUtil.isPhoneNumberValid(phoneNumber) || phoneNumber.length() != 11) {
                    ToastUtils.showToast(R.string.phone_format);
                    return;
                }
                s = 60;
                new Thread(new ClassCut()).start();// 开启倒计时
                params.put("mobile", phoneNumber);
                if (factoryUrl != null && !factoryUrl.equals("")) {
                    HttpUtils.postFirst(mHandlerAll, factoryUrl + "/app/account/sendSms", params, Constants.IMAGESERVLET, LoginActivity.this);
                }
                break;
            case R.id.txt_factory:
                //获取厂
                LogUtil.e("=======获取厂========");
                popupWindow();
                break;
        }
    }

    //获取所有厂家信息
    private void popupWindow() {

        if (popup != null && popup.isShowing()) {
            popup.dismiss();
        } else {
            LayoutInflater inflater = (LayoutInflater) LoginActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View popview = inflater.inflate(R.layout.dialog_set_factory, null);
            ListView mListpop = (ListView) popview.findViewById(R.id.listView);
            adapter = new MyAdapter();
            if (arrayList != null && arrayList.size() > 0) {
                adapter.setmArray(arrayList);
                mListpop.setAdapter(adapter);
            } else {

            }
            popup = new PopupWindow(popview, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
            popup.setFocusable(true);
//          popup.setOutsideTouchable(true);
            popup.setBackgroundDrawable(new BitmapDrawable());
            popup.showAsDropDown(mTxtFactory);
        }
    }

    class ClassCut implements Runnable {// 倒计时逻辑子线程

        @Override
        public void run() {
            // TODO Auto-generated method stub
            while (s > 0) {// 整个倒计时执行的循环
                s--;
                mHandlerAll.post(new Runnable() {// 通过它在UI主线程中修改显示的剩余时间
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        mGetCode.setText("获取验证码" + s + "秒");// 显示剩余时间
                        mGetCode.setClickable(false);
                    }
                });
                try {
                    Thread.sleep(1000);// 线程休眠一秒钟 这个就是倒计时的间隔时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 下面是倒计时结束逻辑
            mHandlerAll.post(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    mGetCode.setText("获取验证码");// 一轮倒计时结束 修改剩余时间为一分钟
                    mGetCode.setClickable(true);
                    // Toast.makeText(MainActivity.this, "倒计时完成",
                    // Toast.LENGTH_LONG).show();//提示倒计时完成
                }
            });
            s = 60;// 修改倒计时剩余时间变量为60秒
        }
    }

    //设置适配器厂家
    class MyAdapter extends BaseAdapter {
        private ArrayList<FactoryNameBean.AddrBean> mArray;
        private int num;

        public MyAdapter() {
        }

        public void setmArray(ArrayList<FactoryNameBean.AddrBean> mArray) {
            this.mArray = mArray;
        }

        @Override
        public int getCount() {
            return mArray != null ? mArray.size() : 0;
        }

        @Override
        public FactoryNameBean.AddrBean getItem(int position) {
            return mArray.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(LoginActivity.this, R.layout.item_factory_name, null);
                holder.mTxtInfo = (TextView) convertView.findViewById(R.id.pop_name);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final int index = position;
            holder.mTxtInfo.setText(mArray.get(position).getName());

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    factoryUrl = mArray.get(index).getUrl();
                    factoryName = mArray.get(index).getName();
                    mTxtFactory.setText(factoryName);
                    if (popup != null && popup.isShowing()) {
                        popup.dismiss();
                    }
                }
            });
            return convertView;
        }
    }

    class ViewHolder {
        TextView mTxtInfo;
    }
}
